//
//  BDMyCouponsListViewController.m
//  iOS_beboy
//
//  Created by wen on 2017/9/21.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDMyCouponsListViewController.h"
#import "BDUserModel.h"
#import "BDMyCouponsModel.h"
#import "BDMyCouponsCell.h"
#import "BDMyCouponsDetailViewController.h"
#import "BDCouponValidationView.h"
#import "BDShopEditCommondViewController.h"

@interface BDMyCouponsListViewController ()<UITableViewDelegate, UITableViewDataSource, BDMyCouponsCellDelegate>

@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation BDMyCouponsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"我的套餐");
    _datasource = [NSMutableArray array];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.startPage = @"1";
        [self requestDatasource];
    }];
    [self.tableView.mj_header beginRefreshing];
}

- (void)requestDatasource{
    [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
    NSString *url = [NSString stringWithFormat:@"%@shopCouponPurchases?page=%@&size=%@", KBDBaseURL, self.startPage, self.pageSize];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer v2_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        [MBManager hideAlert];
        
        if ([self.tableView.mj_header isRefreshing]) {
            [self.datasource removeAllObjects];
            [self.tableView.mj_header endRefreshing];
        }
        
        [self.tableView.mj_footer endRefreshing];
        
        [self.datasource addObjectsFromArray:[BDMyCouponsModel mj_objectArrayWithKeyValuesArray:x[@"list"]]];
        
        self.startPage = x[@"next_page"];
        self.isEnd = [x[@"is_end"] boolValue];
        [self.tableView reloadData];
        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.startPage = @"1";
            [self requestDatasource];
        }];
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self requestDatasource];
        }];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        [MBManager hideAlert];
        if (self.datasource.count == 0) {
            [self showErrorViewWithTapBlock:^{
                [self requestDatasource];
            }];
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _datasource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID = @"couponsCell";
    BDMyCouponsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    cell.delegate = self;
    BDMyCouponsModel *model = _datasource[indexPath.row];
    [cell setModel:model];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kBDMyCouponsCellHeight;
}

- (void)cellDidClick:(BDMyCouponsCell *)cell {
    BDMyCouponsModel *model = cell.couponsView.model;
    if ([model.shopTitle isNotBlank]) {
        BDMyCouponsDetailViewController *couponsDetailVC = [[BDMyCouponsDetailViewController alloc] init];
        couponsDetailVC.couponsModel = model;
        [self.navigationController pushViewController:couponsDetailVC animated:YES];
    }else{
        [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"店铺不存在，无法查看")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
    }
}

- (void)cellDidClickButton:(BDMyCouponsCell *)cell {
    BDMyCouponsModel *model = cell.couponsView.model;
    if (![model.shopTitle isNotBlank]) {
        [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"店铺不存在，无法查看")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
        return;
    }
    switch (model.status) {
        case BDMyCouponsStatusNotUse:{
            BDCouponValidationView *validationView = [BDCouponValidationView couponValidationViewWithCoupons:model];
            [validationView show];
        }break;
        case BDMyCouponsStatusUsed:{
            //评价
            BDShopEditCommondViewController *shopEditCommondVC = [[BDShopEditCommondViewController alloc] init];
            shopEditCommondVC.couponsModel = model;
            [self.navigationController pushViewController:shopEditCommondVC animated:YES];
        }break;
        default:
            break;
    }
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[BDMyCouponsCell class] forCellReuseIdentifier:@"couponsCell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
